/*
 * XmlManager
 * 
 * Copyright 2008-2011 Centro Andaluz de Innovacion y Tecnologias de la
 * Informacion y las Comunicaciones (CITIC). All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 * Please contact CITIC - Edificio CITIC, C/ Marie Curie, 6 Parque
 * Tecnologico de Andalucia 29590 - Campanillas, Malaga, Spain
 * or visit www.citic.es, if you need additional information or
 * have any questions.
 */

package es.citic.puedes.weatherservice.utils;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import es.citic.puedes.weatherservice.WeatherException;

public class XmlManager {
	private String weatherPath = "";

	/**
	 * Log instance
	 */
	public static Logger logger = LoggerFactory.getLogger(XmlManager.class);

	public XmlManager(String weatherPath) {
		this.weatherPath = weatherPath;
	}

	/**
	 * Gets the value of the id property in a config.xml file using the tag and
	 * code for searching the correct value in weather_path.
	 */
	public String getValueFromXmlDocument(String tag, String code, String id)
			throws WeatherException {

		logger.debug("Enter: getValueFromXmlDocument()");

		String propertyValue = null;

		try {
			// Gets the XML
			DocumentBuilderFactory factory = null;
			factory = DocumentBuilderFactory.newInstance();
			factory.setValidating(false);
			DocumentBuilder domBuilder = factory.newDocumentBuilder();

			Document dom = domBuilder.parse(this.weatherPath);

			// Gets the root
			Element element = dom.getDocumentElement();

			// Gets the tag node from the XML file
			NodeList nodeListFromTag = element.getElementsByTagName(tag);
			if (nodeListFromTag == null) {
				throw new WeatherException("the tag " + tag
						+ " does not exist in this config file");
			}

			// gets the child nodes from tag found
			NodeList subtagNodes = nodeListFromTag.item(0).getChildNodes();
			int totalNodes = subtagNodes.getLength();

			// searches the code in the child nodes
			int index = 0;
			boolean codeFound = false;
			Node subtagNodeFound = null;
			while (index <= totalNodes && !codeFound) {

				if (subtagNodes.item(index).getChildNodes().item(1) != null) {

					// if code to search is found..
					if (subtagNodes.item(index).getChildNodes().item(1)
							.getFirstChild().getNodeValue().compareTo(code) == 0) {

						codeFound = true;
						logger.debug("codeFound valee: " + codeFound);

						// gets the node
						subtagNodeFound = subtagNodes.item(index);
					}
				}
				index++;
			}

			// if value of node 'code' is found..
			if (codeFound) {

				if (subtagNodeFound != null) {

					logger.debug("node found: " + subtagNodeFound.getNodeName());

					// gets the property nodes from the node found
					Element propertyElement = (Element) subtagNodeFound;

					NodeList propertyList = propertyElement
							.getElementsByTagName("property");

					int i = 0;
					boolean attributeFound = false;
					Element property_value = null;

					// searches the property node with the 'id' attribute
					while (i < propertyList.getLength() && !attributeFound) {
						property_value = (Element) propertyList.item(i);
						attributeFound = property_value.getAttribute("id")
								.compareTo(id) == 0;
						i++;
					}

					// if the attribute was found..
					if (attributeFound) {
						logger.debug("attribute found?");

						// gets the value for returning
						propertyValue = property_value.getFirstChild()
								.getNodeValue();
					}

				} else {
					throw new WeatherException("Could not find tag " + tag
							+ " in config XML file.");
				}
			}
		} catch (Exception e) {
			throw new WeatherException("Could not load config XML file.");
		}
		logger.debug("Exit: getValueFromXmlDocument()");
		return propertyValue;
	}

}
